package zhibi.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import zhibi.commons.exception.MessageException;
import zhibi.domain.Member;
import zhibi.domain.Orders;
import zhibi.extra.base.BaseController;
import zhibi.extra.pojo.OrdersPo;
import zhibi.extra.pojo.PriceSum;
import zhibi.frame.domain.Page;
import zhibi.frame.mybatis.example.Example;
import zhibi.frame.mybatis.example.ExampleType;
import zhibi.mapper.OrdersMapper;
import zhibi.service.MemberService;
import zhibi.service.OrdersService;
import zhibi.utils.DateUtils;
import zhibi.utils.JSONUtils;
import zhibi.utils.StringUtils;
import zhibi.utils.poi.ExcelUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by 执笔 on 2018/3/24.
 */
@RequestMapping("orders")
@Controller
public class OrdersController extends BaseController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 列表
     *
     * @param orders
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(OrdersPo orders, Page page, Model model,
                       String starttime, String endtime,
                       String starttime1, String endtime1) {
        Example example = Example.getInstance()
                .addParam("o.name", orders.getName(), ExampleType.Operation.LIKE)
                .addParam("o.kefu", orders.getKefu(), ExampleType.Operation.LIKE)
                .addParam("o.status", orders.getStatus())
                .addParam("m.card", orders.getCard(), ExampleType.Operation.LIKE)
                .addParam("o.godate", starttime, ExampleType.Operation.GTE)
                .addParam("o.godate", endtime, ExampleType.Operation.LTE)
                .addParam("o.enrolldate", starttime1, ExampleType.Operation.GTE)
                .addParam("o.enrolldate", endtime1, ExampleType.Operation.LTE)
                .addParam("u.name", orders.getUser(), ExampleType.Operation.LTE)
                .addOrder("o.godate", ExampleType.OrderType.DESC);
        if(!StringUtils.isEmpty(orders.getMember())){
            example.addParam("( m.name like '%"+orders.getMember()+"%' or o.name2 like '%"+orders.getMember()+"%')");
        }
        if(!sessionUser().getType().equals("admin")){
            example.addParam("o.userid",sessionUser().getId());
        }

        PageInfo<OrdersPo> pageInfo = ordersService.selectPoByExample(example, page);
        PriceSum priceSum = ordersMapper.selectSum(example);
        setModelAttribute(model, pageInfo, priceSum);
        return "orders/list";
    }

    /**
     * 导出数据
     *
     * @param orders
     * @param starttime
     * @param endtime
     * @return
     */
    @RequestMapping(value = "list", params = "export")
    public void export(OrdersPo orders, HttpServletResponse response,
                       String starttime, String endtime) throws IOException {
        Example example = Example.getInstance()
                .addParam("o.name", orders.getName(), ExampleType.Operation.LIKE)
                .addParam("o.kefu", orders.getKefu(), ExampleType.Operation.LIKE)
                .addParam("o.status", orders.getStatus())
                .addParam("( m.name like '%"+orders.getMember()+"%' or o.name2 like '%"+orders.getMember()+"%')")
                .addParam("m.card", orders.getCard(), ExampleType.Operation.LIKE)
                .addParam("o.godate", starttime, ExampleType.Operation.GTE)
                .addParam("o.godate", endtime, ExampleType.Operation.LTE)
                .addParam("u.name", orders.getUser(), ExampleType.Operation.LTE)
                .addOrder("o.godate", ExampleType.OrderType.DESC);
        List<OrdersPo> list = ordersService.selectPoByExample(example, new Page(1, Integer.MAX_VALUE)).getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm-ss") + ".xls");
        ExcelUtils.writeExcel(outputStream, list);
    }


    @GetMapping("add")
    public String add(Model model) {
        List<Member> memberList = memberService.selectAll();
        model.addAttribute("memberList", JSONUtils.objToJson(memberList));
        return "orders/add";
    }


    /**
     * 下拉框搜索会员
     *
     * @param key
     * @return
     */
    @GetMapping("searchMember")
    @ResponseBody
    public List<Member> searchMember(@RequestParam(defaultValue = "") String key) {
        Example example = Example.getInstance()
                .addParam("no like '%" + key + "%' or phone like '%" + key
                        + "%' or mobile like '%" + key + "%' or name like '%" + key + "%' or card like '%" + key + "%'");
        return memberService.selectByExample(example);
    }

    @PostMapping("add")
    public String add(Orders orders) {
        orders.setAddtime(new Date());
        orders.setUserid(sessionUser().getId());
        orders.setStatus("wait");
        Date date = DateUtils.parse(orders.getGodate(), "yyyy-MM-dd");
        orders.setBackdate(DateUtils.formatDate(DateUtils.rollDay(date, orders.getDay() - 1), "yyyy-MM-dd"));
        ordersService.insertSelective(orders);
        return redirect("list");
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Orders orders = ordersService.selectByPrimaryKey(id);
        if (null == orders) throw new MessageException("该出行不存在");
        model.addAttribute(orders);
        return "orders/detail";
    }

    @PostMapping("update")
    public String update(Orders orders) {
        orders.setStatus(null);
        ordersService.updateByPrimaryKeySelective(orders);
        return redirect("list");
    }

    @RequestMapping("go/{id}")
    public String go(@PathVariable Integer id) {
        Orders orders = ordersService.selectByPrimaryKey(id);
        if (null == orders) throw new MessageException("该出行不存在");
        //if (!orders.getStatus().equals("wait")) throw new MessageException("该出行已处理");
        orders.setStatus("go");
        ordersService.updateByPrimaryKeySelective(orders);
        return refresh();
    }

    /**
     * 取消
     *
     * @param id
     * @return
     */
    @RequestMapping("cancel/{id}")
    public String cancel(@PathVariable Integer id) {
        Orders orders = ordersService.selectByPrimaryKey(id);
        if (null == orders) throw new MessageException("该出行不存在");
        //if (!orders.getStatus().equals("wait")) throw new MessageException("该出行已处理");
        orders.setStatus("cancel");
        ordersService.updateByPrimaryKeySelective(orders);
        return refresh();
    }

    /**
     * 结算
     *
     * @param id
     * @param balance
     * @return
     */
    @RequestMapping("balance")
    public String balance(Integer id, Double balance) {
        checkAdmin();
        ordersService.balance(id, balance);
        return refresh();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("del/{id}")
    public String del(@PathVariable Integer id) {
        ordersService.deleteByPrimaryKey(id);
        return refresh();
    }

    /**
     * 完成
     *
     * @param id
     * @return
     */
    @RequestMapping("complete")
    public String complete(Integer id) {
        checkAdmin();
        Orders orders = ordersService.selectByPrimaryKey(id);
        orders.setStatus("success");
        ordersService.updateByPrimaryKeySelective(orders);
        return refresh();
    }

}
